package com.acme.domain.account;

import com.acme.exceptions.NoEnoughFundsException;
import com.acme.exceptions.OverDraftLimitExceededException;

public class CheckingAccount extends AbstractAccount {

    private static final long serialVersionUID = -5261983637255563094L;
    private double overdraft;

    public CheckingAccount(final int id, final double amount,
	    final double overdraft) {
	super(id, amount);
	this.overdraft = overdraft;
    }

    @Override
    public void deposit(final double amount) {
	if (amount > 0) {
	    balance += amount;
	} else {
	    throw new IllegalArgumentException("amount ca not be negative");
	}

    }

    @Override
    public AccountType getAccountType() {
	return AccountType.CHECKING;
    }

    public double getOverdraft() {
	return overdraft;
    }

    @Override
    public String toString() {
	return "Checking account with " + overdraft + "$ overdraft. Amount: "
		+ getBalance() + "$";

    }

    @Override
    public double getMaximumAmountToWithdraw() {
	return super.getMaximumAmountToWithdraw() + getOverdraft();
    }
    
    @Override
    public void withdraw(final double amount) throws NoEnoughFundsException {
	if (amount < 0) {
	    throw new IllegalArgumentException("Amount can not be negative");
	}
	if (balance - amount >= -overdraft) {
	    balance -= amount;
	} else {
	    throw new NoEnoughFundsException(amount);
	}

	if (balance < amount) {
	    double overdraftNeeded = amount - balance;
	    if (overdraft < overdraftNeeded) {
		throw new OverDraftLimitExceededException(overdraftNeeded
			- overdraft);
	    }
	    balance = 0.0;
	    overdraft -= overdraftNeeded;
	} else {
	    balance = balance - amount;
	}

	assert (balance >= 0);
	assert (overdraft >= 0);

    }
}
